//
//  Service.swift
//  mycloudmusicswift
//
//  Created by smile on 2019/6/7.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

//导入网络框架
import Moya

/// 定义项目中的所有接口
///
/// - sheetDetail: 歌单详情
/// - sheets: 歌单列表
/// - createSheets: 创建的歌单列表
/// - collectSheets: 收藏的歌单列表
/// - createUser: 创建用户
/// - updateUser: 更新用户
/// - userDetail: 用户详情
/// - bindAccount: 绑定第三方账号
/// - unbindAccount: 解绑第三方账号
/// - resetPassword: 重置密码
/// - follow: 关注用户
/// - deleteFollow: 取消关注用户
/// - sendSMSCode: 发送验证码
/// - sendEmailCode: 发送邮件验证码
/// - ads: 广告列表
/// - songs: 单曲列表
/// - songDetail: 歌曲详情
/// - collect: 收藏歌单
/// - deleteCollect: 取消收藏歌单
/// - comments: 评论列表
/// - createComment: 发布评论
/// - like: 评论点赞
/// - deleteLike: 删除评论点赞
/// - topics: 话题列表
/// - friends: 好友列表
/// - fans: 粉丝列表
/// - videos: 视频列表
/// - videoDetail: 视频详情
/// - feeds: 动态列表
/// - createFeed: 创建动态
/// - searchUsers: 搜索用户
/// - searchSheets: 搜索歌单
/// - searchSuggests: 搜索建议
/// - shops: 商品列表
/// - shopDetail: 商品详情
/// - createOrder: 创建订单
/// - orderDetail: 订单详情
/// - orders: 订单列表
/// - ordersV2: 订单列表V2（响应签名）
/// - createOrderV2: 创建订单V2（参数签名）
/// - ordersV3: 订单列表V3（响应加密）
/// - createOrderV3: 创建订单V3（参数加密）
/// - orderPay: 获取订单支付参数
enum Service {
    case sheetDetail(id:String)
    case sheets
    case createSheets(id:String)
    case collectSheets(id:String)
    case createSheet(title:String)
    
    case createUser(avatar:String?,nickname:String,phone:String,email:String,password:String,qq_id:String?,weibo_id:String?,wechat_id:String?)
    case updateUser(id:String,nickname:String?,avatar:String?,description:String?,gender:Int?,birthday:String?,province:String?,province_code:String?,city:String?,city_code:String?,area:String?,area_code:String?)
    case userDetail(id:String,nickname:String?)
    
    case bindAccount(account:String,platform:Int)
    case unbindAccount(platform:Int)
    
    case login(phone:String?,email:String?,password:String?,qq_id:String?,weibo_id:String?,wechat_id:String?)
    case resetPassword(phone:String?,email:String?,code:String,password:String)
    
    case follow(id:String)
    case deleteFollow(id:String)
    
    case sendSMSCode(phone:String)
    case sendEmailCode(email:String)
    
    case ads
    
    case songs
    case songDetail(id:String)
    
    case collect(id:String)
    case deleteCollect(id:String)
    
    case comments(sheet_id:String?,order:Int,page:Int)
    case createComment(content:String,sheet_id:String?,parent_id:String?)
    
    case like(comment_id:String)
    case deleteLike(id:String)

    case topics
    
    case friends(id:String)
    case fans(id:String)
    
    case videos
    case videoDetail(id:String)
    
    case feeds
    case createFeed(content:String,province:String?,city:String?,longitude:Double?,latitude:Double?,images:[Dictionary<String,String>]?)
    
    case searchUsers(query:String)
    case searchSheets(query:String)
    case searchSuggests(query:String)
    
    case shops
    case shopDetail(id:String)
    
    case createOrder(book_id:String,source:Int)
    
    case orderDetail(id:String)
    case orders
    
    case ordersV2
    case createOrderV2(book_id:String,source:Int)
    
    case ordersV3
    case createOrderV3(book_id:String,source:Int)
    
    case orderPay(id:String,channel:Int,origin:Int)
}

// MARK: - 实现TargetType协议
extension Service: TargetType {
    
    /// 返回网址
    var baseURL: URL {
        return URL(string: ENDPOINT)!
    }
    
    /// 返回每个请求的路径
    var path: String{
        switch self {
        case .sheets, .createSheet:
            return "/v1/sheets"
        case .sheetDetail(let id):
            return "/v1/sheets/\(id)"
        case .createSheets(let id):
            return "/v1/users/\(id)/create"
        case .collectSheets(let id):
            return "/v1/users/\(id)/collect"
            
        case .createUser:
            return "/v1/users"
        case .userDetail(let id, let nickname):
            return "/v1/users/\(id)"
        case .bindAccount:
            return "/v1/users/bind"
        case .unbindAccount(let platform):
            return "/v1/users/\(platform)/unbind"
        case .updateUser(let id, let nickname, let avatar, let description, let gender, let birthday, let province, let province_code, let city, let city_code, let area, let area_code):
            return "/v1/users/\(id)"
            
        case .login:
            return "/v1/sessions"
        case .resetPassword:
            return "/v1/users/reset_password"
            
        case .follow:
            return "/v1/friends"
        case .deleteFollow(let id):
            return "/v1/friends/\(id)"
            
        case .sendSMSCode:
            return "/v1/codes/request_sms_code"
        case .sendEmailCode:
            return "/v1/codes/request_email_code"
            
        case .ads:
            return "/v1/ads"
            
        case .songs:
            return "/v1/songs"
        case .songDetail(let id):
            return "/v1/songs/\(id)"
            
        case .collect:
            return "/v1/collections"
        case .deleteCollect(let id):
            return "/v1/collections/\(id)"
            
        case .comments, .createComment:
            return "/v1/comments"
            
        case .like:
            return "/v1/likes"
        case .deleteLike(let id):
            return "/v1/likes/\(id)"
            
        case .topics:
            return "/v1/topics"
            
        case .friends(let id):
            return "/v1/users/\(id)/following"
        case .fans(let id):
            return "/v1/users/\(id)/followers"
            
        case .videos:
            return "/v1/videos"
        case .videoDetail(let id):
            return "/v1/videos/\(id)"
            
        case .feeds, .createFeed:
            return "/v1/feeds"
            
        case .searchUsers:
            return "/v1/searches/users"
        case .searchSheets:
            return "/v1/searches/sheets"
        case .searchSuggests:
            return "/v1/searches/suggests"
            
        case .shops:
            return "/v1/books"
        case .shopDetail(let id):
            return "/v1/books/\(id)"
            
        case .createOrder, .orders:
            return "/v1/orders"
        case .orderDetail(let id):
            return "/v1/orders/\(id)"
            
        case .ordersV2, .createOrderV2:
            return "/v2/orders"
            
        case .ordersV3, .createOrderV3:
            return "/v3/orders"
            
        case .orderPay(let id, _, _):
            return "/v1/orders/\(id)/pay"
            
        default:
            return ""
        }
    }
    
    /// 请求方式
    var method: Moya.Method {
        switch self {
        case .createUser, .login, .resetPassword, .sendSMSCode, .sendEmailCode, .collect, .createComment, .like, .createSheet, .follow, .createFeed, .bindAccount, .createOrder, .orderPay, .createOrderV2, .createOrderV3:
            return .post
            
        case .deleteCollect, .deleteLike, .deleteFollow, .unbindAccount:
            return .delete
            
        case .updateUser:
            return .patch
            
        default:
            return .get
        }

    }
    
    /// 返回测试相关的数据
    var sampleData: Data {
        return Data()
    }
    
    /// 请求的参数
    var task: Task {
        switch self {
        case .createUser(let avatar, let nickname, let phone, let email, let password, let qq_id, let weibo_id,let wechat_id):
            //将参数编码
            return .requestParameters(parameters: ["avatar":avatar,"nickname":nickname,"phone":phone,"email":email,"password":password,"qq_id":qq_id,"weibo_id":weibo_id,"wechat_id":wechat_id], encoding: JSONEncoding.default)
        case .updateUser(let id, let nickname, let avatar, let description, let gender, let birthday, let province, let province_code, let city, let city_code, let area, let area_code):
            //判断参数
            
            //如果为空
            //服务端现在的实现是清除该字段
            //所以要判断
            var params:[String:Any]=[:]
            
            if let nickname=nickname{
                params["nickname"]=nickname
            }
            
            if let avatar=avatar{
                params["avatar"]=avatar
            }
            
            if let description=description{
                params["description"]=description
            }
            
            if let gender=gender{
                params["gender"]=gender
            }
            
            if let birthday=birthday{
                params["birthday"]=birthday
            }
            
            if let province=province{
                params["province"]=province
                params["province_code"]=province_code!
                
                params["city"]=city!
                params["city_code"]=city_code!
                
                params["area"]=area!
                params["area_code"]=area_code!
            }
            
            return HttpUtil.jsonRequestParamters(params)
            
        case .userDetail(_, let nickname):
            return HttpUtil.urlRequestParamters(["nickname":nickname ?? ""])
            
        case .bindAccount(let account, let platform):
            return HttpUtil.jsonRequestParamters(["account":account,"platform":platform])
            
        case .login(let phone, let email, let password,let qq_id, let weibo_id,let wechat_id):
//            return .requestParameters(parameters: ["phone":phone,"email":email,"password":password,"qq_id":qq_id,"weibo_id":weibo_id], encoding: JSONEncoding.default)
            
            return HttpUtil.jsonRequestParamters(["phone":phone,"email":email,"password":password,"qq_id":qq_id,"weibo_id":weibo_id,"wechat_id":wechat_id])
        case .resetPassword(let phone,let email,let code,let password):
            return HttpUtil.jsonRequestParamters(["phone":phone,"email":email,"code":code,"password":password])
            
        case .follow(let id):
            return HttpUtil.jsonRequestParamters(["id":id])
            
        case .sendSMSCode(let phone):
            return HttpUtil.jsonRequestParamters(["phone":phone])
        case .sendEmailCode(let email):
            return HttpUtil.jsonRequestParamters(["email":email])
            
        case .collect(let id):
            return HttpUtil.jsonRequestParamters(["sheet_id":id])
            
        case .comments(let sheet_id, let order, let page):
            //创建一个字典
            var params:[String:Any] = [:]
            
            //对可选值拆包
            if let sheet_id = sheet_id {
                params["sheet_id"]=sheet_id
            }
            
            //必选值直接设置就行了
            params["order"]=order
            params["page"]=page
            
            return HttpUtil.urlRequestParamters(params)
        case .createComment(let content, let sheet_id, let parent_id):
            return HttpUtil.jsonRequestParamters(["content":content,"sheet_id":sheet_id,"parent_id":parent_id])
            
        case .like(let comment_id):
            return HttpUtil.jsonRequestParamters(["comment_id":comment_id])
            
        case .createSheet(let title):
            return HttpUtil.jsonRequestParamters(["title":title])
            
        case .createFeed(let content,let province,let city,let longtitude,let latitude,let images):
            return HttpUtil.jsonRequestParamters(["content":content,"images":images,"province":province,"city":city,"longtitude":longtitude,"latitude":latitude])
            
        case .searchUsers(let query):
            return HttpUtil.urlRequestParamters(["query":query])
        case .searchSheets(let query):
            return HttpUtil.urlRequestParamters(["query":query])
        case .searchSuggests(let query):
            return HttpUtil.urlRequestParamters(["query":query])
            
        case .createOrder(let book_id, let source):
            return HttpUtil.jsonRequestParamters(["book_id":book_id,"source":source])
            
        case .createOrderV2(let book_id, let source):
            return HttpUtil.jsonRequestParamters(["book_id":book_id,"source":source])
            
        case .createOrderV3(let book_id, let source):
            return HttpUtil.jsonRequestParamters(["book_id":book_id,"source":source])
            
        case .orderPay(_, let channel, let origin):
            return HttpUtil.jsonRequestParamters(["channel":channel,"origin":origin])
            
        default:
            //不传递任何参数
            return .requestPlain
        }
        
    }
    
    /// 请求头
    var headers: [String : String]? {
        
        var headers:Dictionary<String,String> = [:]
        
        //内容的类型
        headers["Content-Type"]="application/json"
        
        //判断是否登录了
        if PreferenceUtil.isLogin() {
            //登录了
            
            let user=PreferenceUtil.userId()
            let token=PreferenceUtil.userToken()
            
            if DEBUG {
                //打印token
                print("Service headers user:\(user),token:\(token)")
            }
            
            //传递登录标识
            headers["User"]=user
            headers["Authorization"]=token
        }
        
        return headers
    }

}

